package cat.joronya.supermanager.europeo.market;

import java.io.IOException;
import java.text.NumberFormat;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import cat.joronya.supermanager.europeo.R;
import cat.joronya.supermanager.europeo.Supermanager;
import cat.joronya.supermanager.europeo.service.SupermanagerServiceHelper;
import cat.joronya.supermanager.europeo.utils.ImageDownloader;

public class MarketListActivity extends ListActivity 
{
	// pel Log
	private static final String TAG = "supermanager";
	
	private static final String POSITION_GUARDS = "GUARD";
	private static final String POSITION_FORWARDS = "FORWARD";
	private static final String POSITION_CENTERS = "CENTER";
	private static final String URL_PHOTO_PLAYER = 
		"http://www.acb.com/fotos_cara/jugadores/J%sLACB57.jpg";
	
	private static final String UP_ARROW = "\u2191";
	private static final String DOWN_ARROW = "\u2193";
	
	/**
     * The columns we are interested in from the database
     */
    private static final String[] PROJECTION = new String[] {
            Supermanager.Market._ID, 				// 0
            Supermanager.Market.ID_PLAYER,			// 1
            Supermanager.Market.STATUS,				// 2
            Supermanager.Market.NACIONALITY,		// 3
            Supermanager.Market.NAME, 				// 4
            Supermanager.Market.INFO,				// 5
            Supermanager.Market.TEAM,				// 6
            Supermanager.Market.BALANCE,			// 7
            Supermanager.Market.AVERAGE,			// 8
            Supermanager.Market.PRICE,				// 9
            Supermanager.Market.MODIFIED_DATE, 		// 10
            Supermanager.Market.CODI_PLAYER,		// 11
            Supermanager.Market.SHOWN_IN_BUY,		// 12
            Supermanager.Market.COLOR_IN_BUY,		// 13
            Supermanager.Market.RATING,				// 14
            Supermanager.Market.RATING_LAST3_GAMES,	// 15
            Supermanager.Market.INCREASE_15,		// 16
            Supermanager.Market.KEEP_PRICE,			// 17
            Supermanager.Market.DECREASE_15,		// 18
            Supermanager.Market.VS_TEAM				// 19
    };
    
    private Cursor cursor = null;
    private Cursor daysCursor = null;
	private String jornada = "?";
	private int selectedPosition = R.id.guards;
	
	// buying player from MyTeamDetail, store position demanded
	private String buyPosition = null;
	private String buyCash = null;
    
	// Gesture detection
    protected MySimpleOnGestureListener mySimpleOnGestureListener;
	protected GestureDetector myGestureDetector;
	protected boolean showingPlayerInfo = false;
	
	protected AbsListView absListView;
	protected ViewFlipper viewFlipper;
	protected static final int SWIPE_MIN_DISTANCE = 60;
	protected static final int SWIPE_MAX_OFF_PATH = 250;
	protected static final int SWIPE_THRESHOLD_VELOCITY = 200;
    
	protected Animation slideLeftIn;
	protected Animation slideLeftOut;
	protected Animation slideRightIn;
	protected Animation slideRightOut;
	
	private NumberFormat decform = null;
    private NumberFormat intform = null;
    
    // filter position: guard, forward or center
    private String position = null;
    
    private final ImageDownloader imageDownloader = new ImageDownloader(this, Supermanager.PLAYERS);

    // order clause with default
	private String order = Supermanager.Market.DEFAULT_SORT_ORDER;
	// mantain order of order clause in pickpup list
	private int orderOnPickupList = 0;
    
	/** 
	 * Called when the activity is first created. 
	 */
	@Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.market);
        
        // amaguem el ProgressBar
        ProgressBar progressBar = (ProgressBar) findViewById(R.id.market_loading);
        progressBar.setVisibility(View.INVISIBLE);
        
        // If no data was given in the intent, then use our default content provider.
        Intent intent = getIntent();

        // have we come from MyTeamDetail to buy player?
        buyPosition = intent.getStringExtra("cat.joronya.supermanager.europeo.myteamdetail.position");
        buyCash = intent.getStringExtra("cat.joronya.supermanager.europeo.myteamdetail.cash");
        
        Uri plUri = getIntent().getData();
        if( plUri == null) {
        	plUri = Supermanager.Market.CONTENT_URI;
            intent.setData(Supermanager.Market.CONTENT_URI);
        }
        
        if( decform == null )
        {
        	decform = NumberFormat.getNumberInstance(new Locale("es","ES"));
        	decform.setMinimumFractionDigits(2);
        }
        if( intform == null )
        {
        	intform = NumberFormat.getNumberInstance(new Locale("es","ES"));
        	intform.setGroupingUsed(true);
        }
        
        // load animations
       	slideLeftIn = AnimationUtils.loadAnimation(this, R.anim.slide_left_in);
        slideLeftOut = AnimationUtils.loadAnimation(this, R.anim.slide_left_out);
        slideRightIn = AnimationUtils.loadAnimation(this, R.anim.slide_right_in);
        slideRightOut = AnimationUtils.loadAnimation(this, R.anim.slide_right_out);
        
        // inicialitzem el detector de gestures, nomes si no estem comprant
        //if( buyPosition == null )
        {
        	// create gesture listener and detector
    		mySimpleOnGestureListener = new MySimpleOnGestureListener();
    		myGestureDetector = new GestureDetector(this, mySimpleOnGestureListener);
        }
        
        // default order
        SharedPreferences settings = 
    		PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        orderOnPickupList = Integer.valueOf(settings.getString(Supermanager.PREFS_MARKET_ORDER, "0"));
        
        // triem criteri ordenacio inicial per defecte
        switch(orderOnPickupList)
        {
        	case 0:
        		order = Supermanager.Market.PRICE_SORT_ORDER;
        		break;
        	case 1:
        		order = Supermanager.Market.AVERAGE_SORT_ORDER;
        		break;
        	case 2:
        		order = Supermanager.Market.RATING_SORT_ORDER;
        		break;
        	case 3:
        		order = Supermanager.Market.RATING_LAST3_GAMES_SORT_ORDER;
        		break;
        	case 4:
        		order = Supermanager.Market.INCREASE_15_SORT_ORDER;
        		break;
        	case 5:
        		order = Supermanager.Market.KEEP_PRICE_SORT_ORDER;
        		break;
        	case 6:
        		order = Supermanager.Market.DECREASE_15_SORT_ORDER;
        		break;
       	}
        
        // recuperem la jornada
        getDaysOfMarket();

        // refresh order mark on header
        updateHeaderOrderMark();
        
        // market view standalone
        if( buyPosition == null )
        {
            // inicialment mostrem ordenat per points
            showMarket(POSITION_GUARDS);
        }
        else
        {
        	// we come from MyTeamDetail, show what we are asked for
        	if( buyPosition.startsWith("b"))
        		showMarket(POSITION_GUARDS);
        	else if( buyPosition.startsWith("a"))
        		showMarket(POSITION_FORWARDS);
        	else
        		showMarket(POSITION_CENTERS);
        }
    }
	
	/**
	 * Gesture listener that responds to:
	 * -fling showing action buttons, +info...
	 * -onLongPress selecting player in buy action from MyTeam.
	 */
	class MySimpleOnGestureListener extends SimpleOnGestureListener 
	{
		private ViewFlipper viewFlipper = null;
		private boolean flipperChanged = false;
		private boolean flipperLongPressed = false;
		
		/**
		 * Sets the view flipper of the last row flinged, so on any event on list,
		 * return view flipper registered to initial status, so hide buttons.
		 * @param theViewFlipper
		 */
		public void setViewFlipper(ViewFlipper theViewFlipper)
		{
			// si tenim longPress pero al mateix flipper, no fem res
			if( flipperLongPressed && viewFlipper == theViewFlipper )
			{
				//Log.d(TAG, "MySimpleOnGestureListener.setViewFlipper longPress and the same flipper, nothing to do.");
				return;
			}
			
			// si ens canvien el flipper, mostrem 1a vista del flipper
			if( viewFlipper != theViewFlipper )
			{
				//Log.d(TAG, "MySimpleOnGestureListener.setViewFlipper different flipper, show previos view.");
				showPreviousOnFlingedRow();
			}
			
			// registrem el flipper de la fila nova
			viewFlipper = theViewFlipper;
		}
		
		/**
		 * For calling externally and return the row to first status.
		 */
		public void showPreviousOnFlingedRow()
		{
			// si el flipper estava canviat, el tornem a lloc
			if( flipperChanged )
			{
				viewFlipper.setInAnimation(slideRightIn);
                viewFlipper.setOutAnimation(slideRightOut);
				viewFlipper.showPrevious();
				flipperChanged = false;
			}
		}
		
		/**
		 * Overriden to avoid 'bug' and prevent onFling from not being called as
		 * described in http://code.google.com/p/android/issues/detail?id=8233
		 */
		@Override
		public boolean onDown(MotionEvent e)
		{
			//Log.d(TAG, "MySimpleOnGestureListener.onDown");
			
			// desmarquem possible previ onLongPress
			flipperLongPressed = false;
			
			return true;
		}
		
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) 
        {
            try 
            {
            	//Log.d(TAG, "MySimpleOnGestureListener.onFling");
            	if( Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH )
                    return false;
                
                // left to right swipe, left fling
                if( e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY ) 
                {
       				flipperChanged = true;
       				viewFlipper.setInAnimation(slideLeftIn);
       				viewFlipper.setOutAnimation(slideLeftOut);
       				viewFlipper.showNext();
                }  
                else if(e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY )
                {
                	// nothing to do on right fling
                }
            	return true;
            }
            catch(Exception e){
                // nothing
            }
            return false;
        }
        
        @Override
        public void onLongPress(MotionEvent e)
        {
        	//Log.d(TAG, "MySimpleOnGestureListener.onLongPress");
        	flipperChanged = true;
			flipperLongPressed = true;
			viewFlipper.setInAnimation(slideLeftIn);
			viewFlipper.setOutAnimation(slideLeftOut);
			viewFlipper.showNext();
        }
    }
	
	
	/**
	 * Select next day. And call show active classificacion.
	 */
	@SuppressWarnings("unused")
	private void selectNextDay()
	{
		if( daysCursor.moveToNext() )
		{
        	jornada = daysCursor.getString(0);
		
        	switch (selectedPosition) 
        	{
        		case R.id.guards:
        			showMarket(POSITION_GUARDS);
        			break;
        		case R.id.forwards:
        			showMarket(POSITION_FORWARDS);
        			break;
        		case R.id.centers:
        			showMarket(POSITION_CENTERS);
        			break;
        	}
        	
        	Log.d(TAG, "MarketListActivity.selectNextDay(): "+jornada);
        	Toast.makeText(MarketListActivity.this, 
        			getResources().getString(R.string.market_activity_next_day, jornada), 
        			Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * Select previous day.
	 */
	@SuppressWarnings("unused")
	private void selectPreviousDay()
	{
		if( daysCursor.moveToPrevious() )
		{
        	jornada = daysCursor.getString(0);
		
        	switch (selectedPosition) 
        	{
        		case R.id.guards:
        			showMarket(POSITION_GUARDS);
        			break;
        		case R.id.forwards:
        			showMarket(POSITION_FORWARDS);
        			break;
        		case R.id.centers:
        			showMarket(POSITION_CENTERS);
        			break;
        	}
        	
        	Log.d(TAG, "MarketListActivity.selectPreviousDay(): "+jornada);
        	Toast.makeText(MarketListActivity.this, 
        			getResources().getString(R.string.market_activity_previous_day, jornada), 
        			Toast.LENGTH_SHORT).show();
		}
	}
	
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.market, menu);
				
        return true;
    }
	
    @Override
	public boolean onPrepareOptionsMenu(Menu menu) 
    {
		for( int i=0;  i<menu.size(); i++) 
		{
			MenuItem menuItem = menu.getItem(i);
			boolean isEnabled = false;
			switch(menuItem.getItemId())
			{
				default:
				case R.id.guards:
				case R.id.forwards:
				case R.id.centers:
				case R.id.refresh:
					isEnabled = ( buyPosition == null );
					break;
				case R.id.order:
					isEnabled = true;
					break;
			}
			menuItem.setEnabled(isEnabled);
		}
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
        // Handle item selection
        switch (item.getItemId()) 
        {
        	case R.id.guards:
        		showMarket(POSITION_GUARDS);
        		return true;
        	case R.id.forwards:
        		showMarket(POSITION_FORWARDS);
        		return true;
        	case R.id.centers:
        		showMarket(POSITION_CENTERS);
        		return true;
        	case R.id.order:
        		// mostrem select per triar ordenacio
        		final CharSequence[] items = {
        				getString(R.string.market_order_by_price),
        				getString(R.string.market_order_by_average),
        				getString(R.string.market_order_by_rating),
        				getString(R.string.market_order_by_rating_last3_games),
        				getString(R.string.market_order_by_increase_15),
        				getString(R.string.market_order_by_keep_price),
        				getString(R.string.market_order_by_decrease_15)};

        		AlertDialog.Builder builder = new AlertDialog.Builder(this);
        		builder.setTitle(getString(R.string.market_order_title));
        		builder.setSingleChoiceItems(items, orderOnPickupList, new DialogInterface.OnClickListener() {
        		    public void onClick(final DialogInterface dialog, int item) 
        		    {
        		        // mantain pick up element
        		        orderOnPickupList = item;
        		        
        		        switch(item)
        		        {
        		        	case 0:
        		        		order = Supermanager.Market.PRICE_SORT_ORDER;
        		        		break;
        		        	case 1:
        		        		order = Supermanager.Market.AVERAGE_SORT_ORDER;
        		        		break;
        		        	case 2:
        		        		order = Supermanager.Market.RATING_SORT_ORDER;
        		        		break;
        		        	case 3:
        		        		order = Supermanager.Market.RATING_LAST3_GAMES_SORT_ORDER;
        		        		break;
        		        	case 4:
        		        		order = Supermanager.Market.INCREASE_15_SORT_ORDER;
        		        		break;
        		        	case 5:
        		        		order = Supermanager.Market.KEEP_PRICE_SORT_ORDER;
        		        		break;
        		        	case 6:
        		        		order = Supermanager.Market.DECREASE_15_SORT_ORDER;
        		        		break;
        		       	}
        		        
        		        // refresh order mark on header
        		        updateHeaderOrderMark();
        		        
        		        // mostrem dades altre cop
                        switch (selectedPosition) 
                    	{
                        	default:
                    		case R.id.guards:
                    			showMarket(POSITION_GUARDS);
                    			break;
                    		case R.id.forwards:
                    			showMarket(POSITION_FORWARDS);
                    			break;
                    		case R.id.centers:
                    			showMarket(POSITION_CENTERS);
                    			break;
                    	}
                        
                        // dismiss dialog, pero deixem seleccionar i despres dismissem
                        new Thread(){
                        	public void run(){
                                dialog.dismiss();
                        	}
                        }.start();
        		    }
        		});
        		builder.create().show();
        		return true;
        	case R.id.refresh:
        		Log.d(TAG,"refreshing market player list");
				// mostrem el ProgressBar
		        ProgressBar progressBar = (ProgressBar) findViewById(R.id.market_loading);
		        progressBar.setVisibility(View.VISIBLE);
		        
				// cridar refresh al REST method
				SupermanagerServiceHelper.getInstance(this).getMarket(handler);
				return true;
        	default:
        		return super.onOptionsItemSelected(item);
        }
    }

    /**
     * Refresh header order arrow mark on every header to notice
     * which order criteria is enabled.
     */
    private void updateHeaderOrderMark()
    {
    	// hide all arrows, so first default string
    	TextView priceView = (TextView)findViewById(R.id.market_price);
    	priceView.setText(getString(R.string.market_price));
    	TextView averageView = (TextView)findViewById(R.id.market_average);
    	averageView.setText(getString(R.string.market_average));
    	TextView ratingView = (TextView)findViewById(R.id.market_rating);
    	ratingView.setText(getString(R.string.market_rating));
    	TextView ratingL3GView = (TextView)findViewById(R.id.market_rating_last3_games);
    	ratingL3GView.setText(getString(R.string.market_last3_games));
    	TextView increase15View = (TextView)findViewById(R.id.market_increase15);
    	increase15View.setText(getString(R.string.market_increase15));
    	TextView keepPriceView = (TextView)findViewById(R.id.market_keep_price);
    	keepPriceView.setText(getString(R.string.market_keep_price));
    	TextView decrease15View = (TextView)findViewById(R.id.market_decrease15);
    	decrease15View.setText(getString(R.string.market_decrease15));
    	
    	// venim de buy del my team detail?
    	TextView cashView = (TextView)findViewById(R.id.market_cash);
    	if( buyCash == null )
    	{
    		cashView.setVisibility(View.GONE);
    	}
    	else
    	{
    		String cashText = getString(R.string.market_cash, buyCash);
    		cashView.setText(cashText);
    		cashView.setVisibility(View.VISIBLE);
    	}
    	
    	// set price arrow
    	switch( orderOnPickupList )
    	{
    		case 0:
    			priceView.setText(getString(R.string.market_price)+DOWN_ARROW);
    			break;
    		case 1:
    			averageView.setText(getString(R.string.market_average)+DOWN_ARROW);
    			break;
    		case 2:
    			ratingView.setText(getString(R.string.market_rating)+DOWN_ARROW);
    			break;
    		case 3:
    			ratingL3GView.setText(getString(R.string.market_last3_games)+DOWN_ARROW);
    			break;
    		case 4:
    			increase15View.setText(getString(R.string.market_increase15)+UP_ARROW);
    			break;
    		case 5:
    			keepPriceView.setText(getString(R.string.market_keep_price)+UP_ARROW);
    			break;
    		case 6:
    			decrease15View.setText(getString(R.string.market_decrease15)+UP_ARROW);
    			break;
    	}

    }
    
    @Override
	protected void onDestroy() 
    {
    	daysCursor.close();
    	if( cursor != null )
    		stopManagingCursor(cursor);
		super.onDestroy();
	}

	/**
	 * Retorna el cursor amb el llistat de jornades disponibles a l'historic
	 * del market.
	 * @return
	 */
	private void getDaysOfMarket()
	{
		 // recuperem el nom de la lliga i la jornada
		MarketProvider marketProvider = new MarketProvider();
		daysCursor = marketProvider.getDays(this);
        
		Log.d(TAG,"MarketListActivity.getDaysOfMarket cursor rows: "+daysCursor.getCount());
		
		// agafem la jornada
        if( daysCursor.moveToLast() )
		{
        	jornada = daysCursor.getString(0);
		}
	}

    @SuppressLint("StringFormatMatches")
	private void showMarket(String position)
    {
    	// guardem la posicio mostrada
        this.position = position;

		// canviem el titol del header per "Mercat: Bases" segons position
        TextView marketTextView = (TextView) findViewById(R.id.market_title);
        
        if( POSITION_GUARDS.equals(position) )
        {
        	selectedPosition = R.id.guards;
        	marketTextView.setText(getResources().getString(R.string.market_title,
        		getResources().getString(R.string.market_menu_guards)));
        }
        else if( POSITION_FORWARDS.equals(position) )
        {
        	selectedPosition = R.id.forwards;
        	marketTextView.setText(getResources().getString(R.string.market_title,
            		getResources().getString(R.string.market_menu_forwards)));
        }
        else if( POSITION_CENTERS.equals(position) )
        {
        	selectedPosition = R.id.centers;
        	marketTextView.setText(getResources().getString(R.string.market_title,
            		getResources().getString(R.string.market_menu_centers)));
        }
        
    	TextView dayView = (TextView) findViewById(R.id.market_day);
    	if( jornada == null )
    		jornada = "";
        dayView.setText(getString(R.string.market_day, jornada));
        
        // tenim cursor?
		if( cursor != null )
			stopManagingCursor(cursor);

		String selection = null;
		String[] selectionArgs = null;
		
		// if we are in buy view, filter only shown players
		if( buyPosition != null )
		{
			selection = Supermanager.Market.POSITION + " = ? AND "+
			   Supermanager.Market.DAY + " = ? AND "+
			   Supermanager.Market.SHOWN_IN_BUY + " = ? ";
			selectionArgs = new String[]{position,jornada,"1"};

		}
		// otherwise all other players
		else
		{
			selection = Supermanager.Market.POSITION + " = ? AND "+
			   Supermanager.Market.DAY + " = ? ";
			selectionArgs = new String[]{position,jornada};
		}
		
		cursor = getContentResolver().query(Supermanager.Market.CONTENT_URI, 
				PROJECTION,	selection, selectionArgs, order );
        
		startManagingCursor(cursor);

        // create market adapter and assign it to view 
        MarketAdapter marketAdapter= new MarketAdapter(this, cursor);
        setListAdapter(marketAdapter);
	}
	
    /**
     * Adapter to customize easily list item layout and values.
     * @author pol
     *
     */
    class MarketAdapter extends CursorAdapter 
	{
		public MarketAdapter(Context theContext, Cursor theCursor) 
		{
			super(theContext, theCursor);
		}
		
		@Override
		public void bindView(View view, Context context, Cursor cursor) 
		{
			//Log.d(TAG,"MarketListActivity bindView for player: "+name);
			
			// set player name
			String name = cursor.getString(4);
			TextView nameView = (TextView)view.findViewById(R.id.player_name);
			nameView.setText(name);
			
			// get idjug, and only set it to tag of the view when black color
			String idJug = cursor.getString(1);

			// show buy button market_row_buy_button
			TextView buyView = (TextView)view.findViewById(R.id.player_buy_button);
			Button buyButton = (Button)view.findViewById(R.id.market_row_buy_button);
			
			// if we are in buy view, set color of player name and buttons
			if( buyPosition != null )
			{
				// set player name to tag for display
				buyButton.setTag(R.id.player_name, name);
				
				// set player idjug to buy
				buyButton.setTag(R.id.market_player, idJug);

				// depenent del color el jugador sera comprable o no
				String color = cursor.getString(13);
				if( Supermanager.Market.RED_COLOR.equals(color.toUpperCase()) )
				{
					nameView.setTextColor(Color.RED);//0xFFF0000);

					// comprant, mostrem botons
					buyView.setVisibility(View.GONE);
					buyButton.setVisibility(View.GONE);

					// player not selectable
					buyButton.setTag(R.id.market_loading, false);
				}
				else if( Supermanager.Market.ORANGE_COLOR.equals(color.toUpperCase()) )
				{
					nameView.setTextColor(0xFFFC7219);

					// comprant, mostrem botons
					buyView.setVisibility(View.GONE);
					buyButton.setVisibility(View.GONE);

					// player not selectable
					buyButton.setTag(R.id.market_loading, false);
				}
				else
				{
					nameView.setTextColor(Color.BLACK);

					// comprant, mostrem botons
					buyView.setVisibility(View.VISIBLE);
					buyButton.setVisibility(View.VISIBLE);

					// player selectable
					buyButton.setTag(R.id.market_loading, true);
				}
			}
			// not buying so, invisible buy buttons
			else
			{
				// no venim del myTeamDetail per comprar
				buyView.setVisibility(View.GONE);
				buyButton.setVisibility(View.GONE);
				
				// by default player not selectable
				buyButton.setTag(R.id.market_loading, false);
			}
			
			// mostrem banda color amb position
			TextView positionView = (TextView)view.findViewById(R.id.position);
			//positionView.setVisibility(View.VISIBLE);
			// bases
			if( POSITION_GUARDS.equals(position) )
			{
				positionView.setText(R.string.market_row_position_guard);
			}
			// alers
			else if( POSITION_FORWARDS.equals(position) )
			{
				positionView.setText(R.string.market_row_position_forward);
			}
			// pivots
			else 
			{
				positionView.setText(R.string.market_row_position_center);
				
			}
			
			// set team player balance
			//String balance = cursor.getString(7);
			//TextView balanceView = (TextView)view.findViewById(R.id.player_balance);
			//balanceView.setText(balance);
			
			// set player team
			String team = cursor.getString(6);
			TextView teamView = (TextView)view.findViewById(R.id.player_team);
			teamView.setText(team);
			
			// set player vs team
			String vsTeam = cursor.getString(19);
			TextView vsTeamView = (TextView)view.findViewById(R.id.player_team_vs);
			vsTeamView.setText(vsTeam);
			
			// setejem l'avatar, la foto del jugador
			@SuppressWarnings("unused")
			String cod = cursor.getString(11);
			ImageView avatarView = (ImageView)view.findViewById(R.id.avatar);
			//imageDownloader.download(String.format(URL_PHOTO_PLAYER, cod), (ImageView) avatarView);
			
			String playerFoto = "photo_players_europeo_2013/"+idJug+".jpg";
			Drawable drawable;
			try {
				drawable = Drawable.createFromStream(getAssets().open(playerFoto), null);
				avatarView.setImageDrawable(drawable);
			} catch (IOException e) {
				//e.printStackTrace();
				avatarView.setImageDrawable(getResources().getDrawable(R.drawable.noavatar));
			}
			
			// set player price
			int price = cursor.getInt(9);
			TextView priceView = (TextView) view.findViewById(R.id.player_price);
			priceView.setText(intform.format(price)+"€");
			
			// set player average
			float average = cursor.getFloat(8);
			TextView averageView = (TextView) view.findViewById(R.id.player_average);
			averageView.setText(decform.format(average));
			
			// set player rating
			float rating = cursor.getFloat(14);
			TextView ratingView = (TextView) view.findViewById(R.id.player_rating);
			ratingView.setText(decform.format(rating));
			
			// set player rating last 3 games
			float ratingLast3Games = cursor.getFloat(15);
			TextView ratingLast3GamesView = (TextView) view.findViewById(R.id.player_rating_last3_games);
			ratingLast3GamesView.setText(decform.format(ratingLast3Games));
			
			// set player increase 15
			float increase15 = cursor.getFloat(16);
			TextView increase15View = (TextView) view.findViewById(R.id.player_increase_15);
			increase15View.setText(decform.format(increase15));
			
			// set player keep price
			float keepPrice = cursor.getFloat(17);
			TextView keepPriceView = (TextView) view.findViewById(R.id.player_keep_price);
			keepPriceView.setText(decform.format(keepPrice));
			
			// set player decrease 15
			float decrease15 = cursor.getFloat(18);
			TextView decrease15View = (TextView) view.findViewById(R.id.player_decrease_15);
			decrease15View.setText(decform.format(decrease15));
			
			// show info view if needed
			String info = cursor.getString(5);
			TextView infoView = (TextView)view.findViewById(R.id.player_info_button);
			Button infoButton = (Button)view.findViewById(R.id.market_row_info_button);
			if( info == null )
			{
				infoView.setVisibility(View.GONE);
				infoButton.setVisibility(View.GONE);
			}
			else
			{
				infoView.setVisibility(View.VISIBLE);
				infoButton.setVisibility(View.VISIBLE);
				infoButton.setTag(info);
			}
			
			// si te status, cal ficar stick corresponent
			String status = cursor.getString(2);
			View stickView = view.findViewById(R.id.stick);
			if( "lesio.png".equals(status) )
			{
				stickView.setVisibility(View.VISIBLE);
				ImageView statusView = (ImageView)stickView;
				statusView.setImageResource(R.drawable.lesio);
				statusView.bringToFront();
			}
			else if( "semafor.png".equals(status) )
			{
				stickView.setVisibility(View.VISIBLE);
				ImageView statusView = (ImageView)stickView;
				// TODO: guardar drawable de semafor
				statusView.setImageResource(R.drawable.lesio);        				
				statusView.bringToFront();
			}
			// altrament mirem si te nationality
			else
			{
				// si te nacionality, cal ficar stick corresponent
				String nacionality = cursor.getString(3);
				if( "nacional.png".equals(nacionality) )
				{
					stickView.setVisibility(View.VISIBLE);
					ImageView statusView = (ImageView)stickView;
					statusView.setImageResource(R.drawable.nacional);
					statusView.bringToFront();
				}
				else if( "extra.png".equals(nacionality) )
				{
					stickView.setVisibility(View.VISIBLE);
					ImageView statusView = (ImageView)stickView;
					statusView.setImageResource(R.drawable.extra);        				
					statusView.bringToFront();
				}
				else if( "bandera_26.png".equals(nacionality) )
				{
					stickView.setVisibility(View.VISIBLE);
					ImageView statusView = (ImageView)stickView;
					statusView.setImageResource(R.drawable.bandera_26);        				
					statusView.bringToFront();
				}
				else if( "bandera_27.png".equals(nacionality) )
				{
					stickView.setVisibility(View.VISIBLE);
					ImageView statusView = (ImageView)stickView;
					statusView.setImageResource(R.drawable.bandera_27);        				
					statusView.bringToFront();
				}
				else if( "bandera_28.png".equals(nacionality) )
				{
					stickView.setVisibility(View.VISIBLE);
					ImageView statusView = (ImageView)stickView;
					statusView.setImageResource(R.drawable.bandera_28);        				
					statusView.bringToFront();
				}
				else if( "bandera_29.png".equals(nacionality) )
				{
					stickView.setVisibility(View.VISIBLE);
					ImageView statusView = (ImageView)stickView;
					statusView.setImageResource(R.drawable.bandera_29);        				
					statusView.bringToFront();
				}
				else if( "bandera_32.png".equals(nacionality) )
				{
					stickView.setVisibility(View.VISIBLE);
					ImageView statusView = (ImageView)stickView;
					statusView.setImageResource(R.drawable.bandera_32);        				
					statusView.bringToFront();
				}
				else if( "bandera_31.png".equals(nacionality) )
				{
					stickView.setVisibility(View.VISIBLE);
					ImageView statusView = (ImageView)stickView;
					statusView.setImageResource(R.drawable.bandera_31);        				
					statusView.bringToFront();
				}
				else if( "bandera_35.png".equals(nacionality) )
				{
					stickView.setVisibility(View.VISIBLE);
					ImageView statusView = (ImageView)stickView;
					statusView.setImageResource(R.drawable.bandera_35);        				
					statusView.bringToFront();
				}
				else if( "bandera_36.png".equals(nacionality) )
				{
					stickView.setVisibility(View.VISIBLE);
					ImageView statusView = (ImageView)stickView;
					statusView.setImageResource(R.drawable.bandera_36);        				
					statusView.bringToFront();
				}
				else if( "bandera_39.png".equals(nacionality) )
				{
					stickView.setVisibility(View.VISIBLE);
					ImageView statusView = (ImageView)stickView;
					statusView.setImageResource(R.drawable.bandera_39);        				
					statusView.bringToFront();
				}
				else if( "bandera_43.png".equals(nacionality) )
				{
					stickView.setVisibility(View.VISIBLE);
					ImageView statusView = (ImageView)stickView;
					statusView.setImageResource(R.drawable.bandera_43);        				
					statusView.bringToFront();
				}
				else if( "bandera_57.png".equals(nacionality) )
				{
					stickView.setVisibility(View.VISIBLE);
					ImageView statusView = (ImageView)stickView;
					statusView.setImageResource(R.drawable.bandera_57);        				
					statusView.bringToFront();
				}
				else if( "bandera_58.png".equals(nacionality) )
				{
					stickView.setVisibility(View.VISIBLE);
					ImageView statusView = (ImageView)stickView;
					statusView.setImageResource(R.drawable.bandera_58);        				
					statusView.bringToFront();
				}
				else if( "bandera_59.png".equals(nacionality) )
				{
					stickView.setVisibility(View.VISIBLE);
					ImageView statusView = (ImageView)stickView;
					statusView.setImageResource(R.drawable.bandera_59);        				
					statusView.bringToFront();
				}
				else if( "bandera_61.png".equals(nacionality) )
				{
					stickView.setVisibility(View.VISIBLE);
					ImageView statusView = (ImageView)stickView;
					statusView.setImageResource(R.drawable.bandera_61);        				
					statusView.bringToFront();
				}
				else if( "bandera_62.png".equals(nacionality) )
				{
					stickView.setVisibility(View.VISIBLE);
					ImageView statusView = (ImageView)stickView;
					statusView.setImageResource(R.drawable.bandera_62);        				
					statusView.bringToFront();
				}
				else if( "bandera_63.png".equals(nacionality) )
				{
					stickView.setVisibility(View.VISIBLE);
					ImageView statusView = (ImageView)stickView;
					statusView.setImageResource(R.drawable.bandera_63);        				
					statusView.bringToFront();
				}
				else if( "bandera_64.png".equals(nacionality) )
				{
					stickView.setVisibility(View.VISIBLE);
					ImageView statusView = (ImageView)stickView;
					statusView.setImageResource(R.drawable.bandera_64);        				
					statusView.bringToFront();
				}
				else if( "bandera_65.png".equals(nacionality) )
				{
					stickView.setVisibility(View.VISIBLE);
					ImageView statusView = (ImageView)stickView;
					statusView.setImageResource(R.drawable.bandera_65);        				
					statusView.bringToFront();
				}
				else if( "bandera_66.png".equals(nacionality) )
				{
					stickView.setVisibility(View.VISIBLE);
					ImageView statusView = (ImageView)stickView;
					statusView.setImageResource(R.drawable.bandera_66);        				
					statusView.bringToFront();
				}
				else if( "bandera_67.png".equals(nacionality) )
				{
					stickView.setVisibility(View.VISIBLE);
					ImageView statusView = (ImageView)stickView;
					statusView.setImageResource(R.drawable.bandera_67);        				
					statusView.bringToFront();
				}
				else if( "bandera_68.png".equals(nacionality) )
				{
					stickView.setVisibility(View.VISIBLE);
					ImageView statusView = (ImageView)stickView;
					statusView.setImageResource(R.drawable.bandera_68);        				
					statusView.bringToFront();
				}
				else if( "bandera_69.png".equals(nacionality) )
				{
					stickView.setVisibility(View.VISIBLE);
					ImageView statusView = (ImageView)stickView;
					statusView.setImageResource(R.drawable.bandera_69);        				
					statusView.bringToFront();
				}
				else if( "bandera_70.png".equals(nacionality) )
				{
					stickView.setVisibility(View.VISIBLE);
					ImageView statusView = (ImageView)stickView;
					statusView.setImageResource(R.drawable.bandera_70);        				
					statusView.bringToFront();
				}
				else if( "bandera_71.png".equals(nacionality) )
				{
					stickView.setVisibility(View.VISIBLE);
					ImageView statusView = (ImageView)stickView;
					statusView.setImageResource(R.drawable.bandera_71);        				
					statusView.bringToFront();
				}
				else
				{
					stickView.setVisibility(View.INVISIBLE);
				}
			}
		}
		
		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) 
		{
			// create the new view
			LayoutInflater inflater = LayoutInflater.from(context);
			ViewFlipper row = (ViewFlipper)inflater.inflate(R.layout.market_row, parent, false);
			
			// bind data to the row view
			bindView(row, context, cursor);	
			
			// if we have player and actions on it, register fling listener
			row.setOnTouchListener(new View.OnTouchListener() 
	        {
	            public boolean onTouch(View v, MotionEvent event) 
	            {
	            	if( showingPlayerInfo )
	            		return true;
	            	
	            	//Log.d(TAG,"MarketAdapter.View.OnTouchListener.onTouch class: "+v.getClass().getName());
	            	
	            	// register row flipper to access it on gesture detector
	            	mySimpleOnGestureListener.setViewFlipper((ViewFlipper)v);
	    			
	            	if (myGestureDetector.onTouchEvent(event)) {
	                    return true;
	                }
	                return false;
	            }
	        });
			
			return row;
		}
	}
    
	/**
	 * Respon al +info button deshabilitant la list i mostrant
	 * el boto de info.
	 * @param view
	 */
	public void showPlayerInfo(View view) 
	{
		// disable list events and grey it
		ListView list = getListView();
		list.setEnabled(false);
		showingPlayerInfo = true;
		
		// enable info button over grey list 
	    Button infoButton = (Button)findViewById(R.id.player_info);
	    infoButton.setText(view.getTag().toString());
	    infoButton.setVisibility(View.VISIBLE);
	}
	
	/**
	 * Respon al click de la info 'modal'. Amaga info i habilita
	 * la list.
	 * @param view
	 */
	public void hidePlayerInfo(View view) 
	{
		// disable info button
	    Button infoButton = (Button)findViewById(R.id.player_info);
	    infoButton.setVisibility(View.GONE);
	    
	    // enable list events and grey off
		ListView list = getListView();
		list.setEnabled(true);
		showingPlayerInfo = false;
	}

	/**
	 * Respon al click del buy, alert i accio de buy.
	 * @param view
	 */
	public void buyPlayer(View view)
	{
    	// if we are in buy, is player selectable?
		final boolean selectable = (Boolean) view.getTag(R.id.market_loading);
		
		// if we are not buying or not selectable, nothing to do here
		if( buyPosition == null || !selectable )
		{
			return;
		}
		// data to show alert to confirm buying this player
		final String idjug = (String)view.getTag(R.id.market_player);
		final String name = (String)view.getTag(R.id.player_name);
		
		AlertDialog alertDialog = new AlertDialog.Builder(MarketListActivity.this).create();
		alertDialog.setTitle(getString(R.string.market_dialog_buy_title));
		alertDialog.setMessage(getString(R.string.market_dialog_buy_message, name));
		alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, 
				getString(R.string.market_dialog_buy_ok),
				new DialogInterface.OnClickListener()
		{
			public void onClick(DialogInterface dialog, int which) 
			{
				Log.d(TAG,"MarketActivityList ok picking player["+name+"] to buy!");
				if( selectable )
				{
					// build result and set it
					Log.d(TAG, "MarketActivityList player["+idjug+"] selected!");
					Intent data = new Intent();
					data.putExtra("cat.joronya.supermanager.europeo.market.buyed_player", idjug);
					setResult(Activity.RESULT_OK, data);
					finish();
				}
				else
				{
					Log.d(TAG, "MarketActivityList player not selectable!");
				}
				return;
			} 
		}); 
		alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
				getString(R.string.market_dialog_buy_cancel),
				new DialogInterface.OnClickListener()
		{
			public void onClick(DialogInterface dialog, int which) 
			{
				Log.d(TAG,"MarketActivityList cancel picking player["+name+"]!");
				return;
			} 
		}); 
		alertDialog.show();
	}
	
    public ImageDownloader getImageDownloader()
    {
        return imageDownloader;
    }
    
    private Handler handler = new Handler() 
    { 
        @Override 
        public void handleMessage(Message msg)
        { 
            //get data from msg 
        	int status = msg.getData().getInt(Supermanager.STATUS_MESSAGE);
            Log.d(TAG, "MarketListActivity received status: "+status);
            
            if( status == Supermanager.MARKET_PARSED_OK )
            {
                // recuperem la jornada, per si em parsejat nova jornada
                getDaysOfMarket();
                
                // mostrem dades altre cop
                switch (selectedPosition) 
            	{
                	default:
            		case R.id.guards:
            			showMarket(POSITION_GUARDS);
            			break;
            		case R.id.forwards:
            			showMarket(POSITION_FORWARDS);
            			break;
            		case R.id.centers:
            			showMarket(POSITION_CENTERS);
            			break;
            	}

            	// amaguem el ProgressBar
		        ProgressBar progressBar = (ProgressBar) findViewById(R.id.market_loading);
		        progressBar.setVisibility(View.INVISIBLE);
		        
		        Toast.makeText(getApplicationContext(), 
            		R.string.market_toast_refresh_done, 
            		Toast.LENGTH_SHORT).show();
            }
            else if( status == Supermanager.CLOSED_STATUS )
            {
            	// amaguem el ProgressBar
		        ProgressBar progressBar = (ProgressBar) findViewById(R.id.market_loading);
		        progressBar.setVisibility(View.INVISIBLE);
		        
		        Toast.makeText(getApplicationContext(), 
            		R.string.market_toast_refresh_fail_changes_closed, 
            		Toast.LENGTH_SHORT).show();
            }
            // altrament error
            else
            {
            	// amaguem el ProgressBar
		        ProgressBar progressBar = (ProgressBar) findViewById(R.id.market_loading);
		        progressBar.setVisibility(View.INVISIBLE);
		        
		        Toast.makeText(getApplicationContext(), 
		        	R.string.market_toast_refresh_fail, 
            		Toast.LENGTH_SHORT).show();
            }
            
            super.handleMessage(msg); 
        } 
    };

}
